package com.xuecheng.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLEncoder;

/**
 * @author Sober_wxy
 * @date 2022/7/16 16:50
 * 交给spring容器管理
 * 通过此过滤器 完成token 鉴权
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
        @SneakyThrows
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // 获取请求 响应对象
                ServerHttpRequest request = exchange.getRequest();
                ServerHttpResponse response = exchange.getResponse();
                // 过滤不需要校验token 的 请求路径
                String path = request.getURI().getPath();
                if(path.contains("coursePub/preview") ||
                        path.contains("auth/login") ||
                        path.contains("basic/dictionary") ||
                        path.contains("category/tree-nodes") ||
                        path.contains("course/upload") ||
                        path.contains("search/") ||
                        path.contains("system/company") ){
                        return chain.filter(exchange);
                }
                // 获取token
                String token = request.getHeaders().getFirst("Authorization");
                // 校验token 返回401状态码 UNAUTHORIZED
                Boolean verifyToken = JwtUtils.verifyToken(token);
                if(!verifyToken){
                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
                        return response.setComplete();
                }
                // 解析token  封装java对象
                AuthInfo authInfo = JwtUtils.getInfoFromToken(token);
                // 向下传递 到其他微服务
                // 向请求头对象 封装对象信息
                String json = URLEncoder.encode(JSON.toJSONString(authInfo), "UTF-8");
                ServerHttpRequest payload = request.mutate().headers(httpHeaders -> {
                        httpHeaders.set("payload", json);
                }).build();
                exchange.mutate().request(payload);
                // 放行
                return chain.filter(exchange);
        }

        /**
         * 过滤器 优先级设置   （过滤器链 需要有先后顺序 因此设置优先级）
         * @return 级别码
         */
        @Override
        public int getOrder() {
                return 0;
        }
}
